package com.zhangxin.aiInterview.manager.work_flow.ai_hr_interviewer.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.manager.work_flow.ai_hr_interviewer.constants.CozeConstants;
import com.zhangxin.aiInterview.manager.wsserver.WsManager;
import com.zhangxin.aiInterview.manager.wsserver.enums.WsMessageTypeEnum;
import com.zhangxin.aiInterview.manager.wsserver.model.WsResponseMessage;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取对话详情
 */
@Service
public class GetHrChatDetail {
    @Resource
    private ClearHrConversationContext clearHrConversationContext;

    /**
     * 获取第一个回答中的 code 和 content 字段
     * @param conversationId 会话id
     * @param chatId 对话id
     * @param userId 用户id
     * @return 拼接后的内容
     */
    public String getFirstContent(String conversationId, String chatId,Long userId) {
        try {
            String url = "https://api.coze.cn/v3/chat/message/list?chat_id=" + chatId + "&conversation_id=" + conversationId;

            HttpResponse response = HttpRequest.get(url)
                    .header("Authorization", CozeConstants.TOKEN)
                    .header("Content-Type", "application/json")
                    .execute();

            JSONObject result = JSONUtil.parseObj(response.body());
            JSONArray dataArray = result.getJSONArray("data");

            if (dataArray != null && !dataArray.isEmpty()) {
                JSONObject firstObject = dataArray.getJSONObject(0);
                String contentRaw = firstObject.getStr("content");

                System.out.println("=================");
                String pattern = "^```json\\s*([\\s\\S]*?\\}\\s*)(?:```|$)";
                Pattern regex = Pattern.compile(pattern);
                Matcher matcher = regex.matcher(contentRaw);

                if (matcher.find()) {
                    contentRaw = matcher.group(1).trim();
                }
                System.out.println(contentRaw);

                // content 是 JSON 字符串
                JSONObject parsedContent = JSONUtil.parseObj(contentRaw);
                Integer code = parsedContent.getInt("code");
                String content = parsedContent.getStr("content");
                //如果code为2表示面试结束
                if(code == 2){
                    //获取客户端ws连接
                    WebSocketSession session = WsManager.getConnection(userId);
                    WsResponseMessage wsResponseMessage = new WsResponseMessage(WsMessageTypeEnum.FINISH.getValue(), "");
                    //返回结束信息给客户端
                    session.sendMessage(new TextMessage(JSONUtil.toJsonStr(wsResponseMessage)));
                    //清除当前会话上下文
                    boolean success = clearHrConversationContext.clear(conversationId);
                    if (success) {
                        System.out.println("清除上下文成功");
                    } else {
                        System.out.println("清除上下文失败");
                    }
                }
                return content;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "未获取到任何消息";
    }
}
